package cn.tedu.mall.book.ex.handler;

import cn.tedu.mall.book.ex.ServiceException;
import cn.tedu.mall.book.web.JsonResult;
import cn.tedu.mall.book.web.State;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author zxjun
 * @date 2022/6/13 14:27
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handlerServiceException(ServiceException e){
        return JsonResult.fail(e.getState(),e.getMessage());
    }

    // 线程安全问题:多个线程同时修改同一个量
    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handlerBindException(BindException e){
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            stringBuilder.append(";");
            stringBuilder.append(fieldError.getDefaultMessage());
        }
        String message = stringBuilder.substring(1);
        return JsonResult.fail(State.ERR_BAD_REQUEST,message);
    }
}
